<template>
  <div class="add-dept">
    <div v-loading.fullscreen.lock="loading"></div>
    <el-dialog :title="currentType.title" :visible="isShowDialog" @close="closeClick">
      <el-form label-width="100px" ref="form" :model="form" :rules="rules">
        <el-form-item label="部门名称" prop="name">
          <el-input placeholder="1-50个字符" v-model="form.name"/>
        </el-form-item>
        <el-form-item label="部门编码" prop="code">
          <el-input placeholder="1-50个字符" v-model="form.code"/>
        </el-form-item>
        <el-form-item label="部门负责人" prop="manager">
          <el-select placeholder="请选择" v-model="form.manager">
            <el-option
              v-for="item in managerList" :key="item.id" :label="item.username" :value="item.username"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="部门介绍" prop="introduce">
          <el-input placeholder="1-300个字符" v-model="form.introduce"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeClick">取 消</el-button>
        <el-button :type="currentType.type" @click="confirmClick">{{ currentType.confirmText }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
//校验的规则
// import {checkNameRepeat} from "@/utils/validate";
import {checkCodeRepeat} from "@/utils/validate";
//引入网络请求
import {addDepartmentApi, companyDepartmentApi, updateDepartmentApi} from "@/api/departments";
import {getSimpleApi} from "@/api/employees";

export default {
  name: "addDept",
  props: {
    isShowDialog: {
      type: Boolean,
      default: false
    },
    //新增部门的父级的数据  type属性保存当前要操作的类型
    currentItem: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  computed: {
    currentType() {
      if (this.currentItem.type === 'add') return {title: '新增部门', type: 'primary', confirmText: '新增'}
      return {title: '编辑部门', type: 'success', confirmText: '修改'}
    }
  },
  methods: {
    //确定按钮
    confirmClick() {
      //调用form表单的全局校验规则
      this.$refs.form.validate(async isPass => {
        if (isPass) {
          this.loading = true
          try {
            if (this.currentItem.type === 'add') {
              //提交新增数据
              await addDepartmentApi({...this.form, pid: this.currentItem.pid === '-1' ? "" : this.currentItem.id})
            } else {
              //提交编辑后的数据
              await updateDepartmentApi(this.form)
            }
            //关闭新增面板并清空表单数据   调用close按钮
            // this.$emit('closeDialog')
            this.closeClick()
            //提示修改成功
            this.$message.success('操作成功')
            //更新页面刷新
            this.$emit('listUpdate')
            this.loading = false
          } catch {
            console.log('新增部门错误')
          }
        }
      })
    },
    //取消按钮
    closeClick() {
      //重置form和移除校验结果
      this.$refs.form.resetFields()
      this.form = {
        code: '', //部门编码，同级部门不可重复
        introduce: '', //部门介绍
        manager: '', //负责人名称
        name: '', //部门名称
        pid: '' //父级部门id
      }
      this.$emit('update:isShowDialog', false)
    }
  },
  data() {
    return {
      //表单对象
      form: {
        code: '', //部门编码，同级部门不可重复
        introduce: '', //部门介绍
        manager: '', //负责人名称
        name: '', //部门名称
        pid: '' //父级部门id
      },
      //校验规则
      rules: {
        code: [
          {required: true, message: '部门编码不能为空', trigger: 'blur'},
          {min: 1, max: 50, message: '字符长度必须为1-50', trigger: 'blur'},
          {
            validator: async (rule, value, callback) => {
              // 先获取最新的组织架构数据
              const {depts} = await companyDepartmentApi()
              let isRepeat = null
              // console.log(value)
              // console.log(id)
              // depts是所有部门的数据
              //新增规则
              if (this.currentItem.type === 'add') {
                isRepeat = depts.some(v => v.code === value && value)
              } else {
                isRepeat = depts.some(item => item.id !== this.currentItem.id && item.code === value && value)
              }
              isRepeat ? callback(new Error(`部门编码${value}已存在`)) : callback()
            }, trigger: 'blur'
          }
        ],
        name: [
          {required: true, message: '部门名称不能为空', trigger: 'blur'},
          {min: 1, max: 50, message: '字符长度必须为1-50', trigger: 'blur'},
          {
            validator: async (rule, value, callback) => {
              // 先获取最新的组织架构数据
              const {depts} = await companyDepartmentApi()
              let isRepeat = null
              // depts是所有部门的数据
              //筛选出子部门并且判断有无重复部门名称
              // 新增规则
              if (this.currentItem.type === 'add') {
                isRepeat = depts.some(v => v.pid === this.currentItem.id && v.name === value)
              } else {
                //编辑规则
                isRepeat = depts.filter(item => item.pid === this.currentItem.pid).some(v => v.name === value && v.id !== this.currentItem.id)
              }
              isRepeat ? callback(new Error(`同级部门下已经有${value}部门了`)) : callback()
            }, trigger: 'blur'
          }
        ],
        manager: [
          {required: true, message: '部门负责人不能为空', trigger: 'blur'},
        ],
        introduce: [
          {required: true, message: '部门介绍不能为空', trigger: 'blur'},
          {min: 1, max: 300, message: '字符长度必须为1-300', trigger: 'blur'},
        ]
      },
      //负责人下拉的数据list
      managerList: null,
      //是否显示加载中
      loading: false
    }
  },
  async created() {
    this.managerList = await getSimpleApi()
    // console.log(res)
  }
}
</script>

<style scoped lang="scss">
.add-dept {
  ::v-deep .el-form-item__label {
    font-weight: 500;
  }
}
</style>
